package lc;

import java.util.HashMap;
import java.util.Map;

/**
 * 分离题目与答案
 * <p>
 * 需要自行在 answer 模块中创建个类，并在静态代码块中添加绑定代码
 * <pre>
 * class LcInit {
 *
 *     static {
 *         LcProjects.register(Y22M04.class, Y22M04Impl.class);
 *         LcProjects.register(Contest288.class, Contest288Impl.class);
 *     }
 * }
 * </pre>
 */
public class LcProjects {

    private static final Map<Class<?>, Class<?>> IMPL_MAPS = new HashMap<>();

    static {
        try {
            Class.forName("lc.LcInit");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static <T> void register(Class<T> interfaceClazz, Class<? extends T> implClazz) {
        IMPL_MAPS.put(interfaceClazz, implClazz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T createImpl(Class<T> clazz) {
        Class<?> implClazz = IMPL_MAPS.get(clazz);
        if (implClazz == null) {
            throw new RuntimeException("未注册的类");
        }

        try {
            return (T) implClazz.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
